class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        sort(nums.begin(), nums.end());
        std::vector<vector<int>> vv;
        int sz = nums.size();
        for(int i = 0; i < sz - 3;)
        {
            for(int j = i + 1; j < sz - 2;)
            {
                long target_2 = target - (long)nums[i] - (long)nums[j];
                int left = j + 1, right = sz - 1;
                while(left < right)
                {
                    int sum = nums[left] + nums[right];
                    if(sum < target_2)
                    {
                        left++;
                    }
                    else if(sum > target_2)
                    {
                        right--;
                    }
                    else if(sum == target_2)
                    {
                        vv.push_back({nums[left++], nums[right--], nums[i], nums[j]});
                        while(left < right && nums[left] == nums[left - 1])
                        {
                            left++;
                        }
                        while(left < right && nums[right] == nums[right + 1])
                        {
                            right--;
                        }
                    }
                }
                j++;
                while(j < sz - 2 && nums[j] == nums[j - 1]) j++;
            }
            i++;
            while(i < sz - 3 && nums[i] == nums[i - 1]) i++;
        }
        return vv;
    }
};